package dingo

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"yundian/internel/pkg/dingo/global"
	. "yundian/internel/pkg/dingo/result"
)

// panic 请求错误拦截
func ErrorHandler() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				if e, ok := err.(validator.ValidationErrors); ok {
					Response(ctx)("", CodeInvalidParam, e.Translate(global.Trans))(Error)
					return
				}
				if e, ok := err.(error); ok && e.Error() == "EOF" {
					Response(ctx)("", CodeForbidden, err)(Forbidden)
					return
				}
				zap.L().Error(CodeInternalServerError.Msg(), zap.Error(err.(error)))
				Response(ctx)("", CodeInternalServerError, err)(ServerError)
				return
			}
		}()
		ctx.Next()
	}
}
